package com.teacher.service.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.teacher.pojo.entity.ClassLevel;
import com.teacher.pojo.entity.RewardDistribution;
import com.teacher.pojo.entity.StuClass;
import com.teacher.pojo.enums.ClassLevelType;
import com.teacher.pojo.excel.ClassLevelExcel;
import com.teacher.pojo.excel.RewardDistributionExcel;
import com.teacher.service.IClassLevelService;
import com.teacher.service.IRewardDistributionService;
import com.teacher.service.IStuClassService;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: zfm
 * @Date: 2021/7/30 16:17
 */
public class ExcelRewardDistributionListener extends AnalysisEventListener<RewardDistributionExcel> {
    private Long termId;
    private IRewardDistributionService iRewardDistributionService;

    private List<RewardDistribution> rewardDistributionList = new ArrayList<>();
    private IStuClassService iStuClassService;

    public ExcelRewardDistributionListener(Long termId, IRewardDistributionService iRewardDistributionService, IStuClassService iStuClassService) {
        this.termId = termId;
        this.iRewardDistributionService = iRewardDistributionService;
        this.iStuClassService = iStuClassService;
    }

    @Override
    public void invoke(RewardDistributionExcel rewardDistributionExcel, AnalysisContext analysisContext) {
        StuClass stuClass = iStuClassService.getOne(new QueryWrapper<StuClass>().lambda()
                .eq(StuClass::getClassName, rewardDistributionExcel.getClassName()).last("limit 1"));
        if (stuClass != null) {
            RewardDistribution rewardDistribution = new RewardDistribution();
            BeanUtils.copyProperties(rewardDistributionExcel, rewardDistribution);
            rewardDistribution.setTermId(termId);
            rewardDistribution.setClassId(stuClass.getId());
            rewardDistributionList.add(rewardDistribution);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
    }

    private void saveData() {
        iRewardDistributionService.saveBatch(rewardDistributionList);
    }
}
